<template>
  <el-dialog
    :title="pageType === 'add' ? '新增' : pageType !== 'detail' ? '修改' : '详情' "
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-button v-show="pageType === 'add'" type="primary" @click="addProduct" style="margin-bottom: 10px"
    >添加秒杀产品</el-button
    >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <div v-for="(item, i) in dataForm.productList" :key="i" class="border">
        <el-row type="flex" align="middle">
          <el-col :span="16">
            <el-form-item label="秒杀产品" :prop="'productList.' + i + '.productId'" :rules="dataRule.productId">
              <el-select
                :disabled="pageType !== 'add'"
                v-model="item.productId"
                @change="changeFn"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dataList"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                  :disabled="editData.map(d=>d.productId).indexOf(item.productId)  !== -1"
                >
                </el-option>
                <el-pagination
                  layout="prev, pager, next"
                  @current-change="currentChangeHandle"
                  :current-page="proPage"
                  :total="totalPage">
                </el-pagination>
              </el-select>
            </el-form-item>
            <el-form-item label="库存" :prop="'productList.' + i + '.totalCount'" :rules="dataRule.totalCount">
              <el-input
                :disabled="pageType === 'detail'"
                v-model="item.totalCount"
                placeholder="请输入秒杀库存"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="秒杀价格" :prop="'productList.' + i + '.seckillPrice'" :rules="dataRule.seckillPrice">
              <el-input
                :disabled="pageType === 'detail'"
                v-model="item.seckillPrice"
                placeholder="请输入秒杀价格"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :push="3">
            <el-button v-show="pageType !== 'detail' && !item.default"  @click="delFn(item, i, dataForm.productList)" type="danger">删除</el-button>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <span v-show="pageType !== 'detail'" slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      roleList: [],
      pageType: '',
      dataForm: {
        productList: [{
          productId: '',
          totalCount: '',
          seckillPrice: ''
        }]
      },
      editData: [],
      dataList: [],
      dataRule: {
        productId: [
          { required: true, message: '请选择需要秒杀的产品', trigger: 'change' }
        ],
        totalCount: [
          { required: true, message: '请输入库存数量', trigger: 'change' }
        ],
        seckillPrice: [
          { required: true, message: '请输入秒杀价格', trigger: 'change' }
        ]
      },
      rowData: {},
      statusFlag: 'add',
      proPage:1,
      totalPage: 0
    }
  },
  watch: {
    'dataForm.productList': {
      handler (newVal, oldVal) {
        console.log(newVal, oldVal)
        this.dataList.map((item, i) => {
          newVal.map((v, k) => {
            if (item.productId === v.productId) {
              item.selected = true
            } else {
              item.selected = false
            }
          })
        })
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    init (row, type) {
      // this.statusFlag = statusFlag  // 'update' 'add'
      this.dataForm.id = (row && row.id) || 0
      this.rowData = row || {}
      this.pageType = type
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
      })
      
      this.$http({
        url: this.$http.adornUrl('/coupon/coupon/product/list'),
        method: 'get',
        params: this.$http.adornParams({
          page: 1,
          limit: 100
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.list.map((item, i) => {
            item.selected = false
          })
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })

      this.$http({
        url: this.$http.adornUrl(
          `/coupon/coupon/productsession/list`
        ),
        method: 'get',
        params: this.$http.adornParams({
          page: 1,
          limit: 10,
          sessionId: this.dataForm.id
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          let list = data.page.list
          list.map((item, i) => {
            item.default = true
          })
          if(this.pageType === 'add'){
            this.dataForm.productList = []
            this.editData = list
          } else {
            this.dataForm.productList = list
          }
        }
      })
      this.visible = true
    },
    getProductList() {
      this.$http({
        url: this.$http.adornUrl('/coupon/coupon/product/list'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.proPage,
          limit: 100
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.list.map((item, i) => {
            item.selected = false
          })
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 秒杀产品翻页
    currentChangeHandle (val) {
      debugger
      this.proPage = val
      this.getProductList()
    },
    // 添加秒杀产品
    addProduct () {
      let obj = {
        productId: '',
        totalCount: '',
        seckillPrice: ''
      }
      this.dataForm.productList.push(JSON.parse(JSON.stringify(obj)))
    },
    // 切换选择框
    changeFn (v) {
      this.dataList.map((item, i) => {
        if (item.productId === v.productId) {
          item.selected = true
        }
      })
    },
    // 删除添加的产品
    delFn (v, i, l) {
      if (l.length === 1) {
        return false
      }
      this.dataList.map((item, i) => {
        if (item.productId === v.productId) {
          item.selected = false
        }
      })
      this.dataForm.productList.splice(i, 1)
    },
    // 表单提交
    dataFormSubmit () {
      console.log(this.dataForm)
      let productList = []
      if (this.pageType === 'add') {
        this.dataForm.productList.map((item, i) => {
          productList.push({
            productId: item.productId,
            totalCount: item.totalCount,
            seckillPrice: item.seckillPrice
          })
        })
      } else {
        this.dataForm.productList.map((item, i) => {
          productList.push({
            productId: item.productId,
            totalCount: Number(item.totalCount),
            seckillPrice: Number(item.seckillPrice),
            sessionId: this.rowData.id || undefined,
            sessionName: this.rowData.sessionName,
            endTime: this.rowData.endTime,
            startTime: this.rowData.startTime
          })
        })
      }
      console.log(this.dataForm.productList)
      console.log(productList)
      debugger
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.dataForm)
          this.$http({
            url: this.$http.adornUrl(
              `/coupon/coupon/${
                this.pageType === 'add' ? 'productsession/saveNew' : 'product/update'
              }`
            ),
            method: 'post',
            data: this.$http.adornData(this.pageType === 'add' ? {
              productList: productList,
              sessionId: this.rowData.id || undefined,
              sessionName: this.rowData.sessionName,
              endTime: this.rowData.endTime,
              startTime: this.rowData.startTime
            } : productList, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
.border + .border {
  border-top: 1px solid #dedede;
  padding-top: 20px;
}
</style>
